/* eslint-disable @typescript-eslint/no-use-before-define */
import { getArticles, getArticlesById } from '@/services/ant-design-pro/knowledge';
import { DataType } from '@/services/models/dataDoc';
import { getFileSize } from '@/utils';
import { message, Space, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import styles from './index.less';

const DataSel: React.FC<any> = (props: any) => {
  const { selDataDoc } = props;
  const [romKey] = useState<number>(1000);
  const [dataSource, setDataSource] = useState<DataType[]>();
  const [selIndex, setSelIndex] = useState<number>(-1);
  const [totals, setTotals] = useState<number>();
  //分页默认值，
  const [pageOption, setPageOption] = useState({
    pageNo: 1, //当前页为1
    pageSize: 10, //一页8行
  });

  const selRow = async (index: number) => {
    const selItem = dataSource[index];
    const res = await getArticlesById(selItem.article_id);
    if (res.code === 0) {
      selDataDoc(res.data?.content);
      selItem.select = true;
      if (selIndex > -1) {
        const oldSelItem = dataSource[selIndex];
        oldSelItem.select = false;
      }
      setSelIndex(index);
      // setRomKey(romKey + 10);
      // const datasCopy = [...dataSource]
      // setDataSource(datasCopy)
    } else {
      message.error(res.msg);
    }
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      width: 50,
      className: `${styles.f11}`,
      render: (text, record, index) =>
        `${(pageOption.pageNo - 1) * pageOption.pageSize + (index + 1)}`,
    },
    {
      title: '文档标题',
      className: `${styles.f11}`,
      dataIndex: 'title',
    },
    {
      title: '上传时间',
      width: 140,
      dataIndex: 'created_at',
      className: `${styles.f11}`,
      render: (_, record) => `${moment(parseInt(record.created_at)).format('YYYY.MM.DD HH:mm:ss')}`,
    },
    {
      title: '上传人',
      className: `${styles.f11}`,
      width: 80,
      dataIndex: 'created_by',
    },
    {
      title: '文件大小',
      className: `${styles.f11}`,
      width: 70,
      dataIndex: 'length',
      render: (_, record) => `${getFileSize(record.length)}`,
    },
    {
      title: '操作',
      key: 'action',
      className: `${styles.f11}`,
      width: 60,
      render: (_, record, index) => (
        <Space>
          {!record.select ? (
            <a onClick={() => selRow(index)}>选择</a>
          ) : (
            <span style={{ color: 'rgba(0,0,0,0.4)' }}>已选</span>
          )}
        </Space>
      ),
    },
  ];

  const articleRes = async (current: number, size: number) => {
    const res = await getArticles({ page: current, per_page: size });
    if (res.code === 0) {
      const { articles, total_count } = res.data;
      setTotals(total_count);
      articles.forEach((article: any) => {
        article.key = +new Date() + Math.random();
      });
      setDataSource(articles);
    } else {
      message.error(res.msg);
    }
    return;
  };

  useEffect(() => {
    articleRes(pageOption.pageNo, pageOption.pageSize);
  }, []);

  //分页配置
  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: () => `共${totals}条`,
    current: pageOption.pageNo,
    pageSize: pageOption.pageSize,
    total: totals,
    onChange: (current: number, size: number) => paginationChange(current, size),
  };

  //当翻页时，改变当前为第current页，current和size这两参数是onChange API自带的，会帮你算出来你现在在第几页，这一页有多少行数据。
  const paginationChange = async (current: number, size: number) => {
    //前面用到useState
    setPageOption({
      pageNo: current, //当前所在页面
      pageSize: size, //一页有几行
    });

    articleRes(current, size);
  };

  const rowClassName = (record: any) => {
    let className = styles['light-row'];
    // if (index % 2 === 1) className = styles['dark-row'];
    if (record.select) className = styles['sel'];
    return className;
  };

  return (
    <div className={styles.containData}>
      <Table
        key={romKey}
        columns={columns}
        className={'custom-table-style'}
        dataSource={dataSource}
        rowClassName={rowClassName}
        pagination={paginationProps}
        scroll={{ y: 500 }}
        size="small"
      />
    </div>
  );
};

export default DataSel;
